package com.ph.seata.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ph.seata.account.dto.AccountDTO;
import com.ph.seata.account.service.AccountFeignService;
import com.ph.seata.order.dto.OrderDTO;
import com.ph.seata.order.mapper.OrderMapper;
import com.ph.seata.order.model.OrderDO;
import com.ph.seata.order.service.OrderService;
import com.ph.web.common.response.WrapperResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author swallow
 * @since 2021-06-29
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderDO> implements OrderService {

    @Autowired
    private AccountFeignService accountFeignService;

    @Override
    @Transactional
    public WrapperResponse<OrderDTO> createOrder(OrderDTO orderDTO) {

        //扣减用户账户
        AccountDTO accountDTO = new AccountDTO()
                .setUserId(orderDTO.getUserId())
                .setAmount(orderDTO.getOrderAmount());
        WrapperResponse<Object> accountResponse = accountFeignService.decAccount(accountDTO);
        if (accountResponse.getCode() != 0) {
            return WrapperResponse.buildError("扣减用户账户失败:" + accountResponse.getMsg());
        }
        //生成订单号
        orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        //生成订单
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(orderDTO, orderDO);
        orderDO.setCount(orderDTO.getOrderCount());
        orderDO.setAmount(orderDTO.getOrderAmount().doubleValue());
        try {
            baseMapper.createOrder(orderDO);
        } catch (Exception e) {
            return WrapperResponse.buildError("插入订单失败:" + e.getLocalizedMessage());
        }
        BeanUtils.copyProperties(orderDO, orderDTO);
        return WrapperResponse.buildSuccess(orderDTO);
    }
}
